using System;
using System.Collections.Generic;
using System.Text;
using Lizk.SimpleHUD;
using System.IO;
using System.Xml.Serialization;
using MediaData;

namespace SharpMedia.Pages
{
    public class FileBrowserPage : MediaPage
    {
        HUDContainerSimple mainBrowser, quickLinks;
        HUDMoveList list, linkList;
        HUDImage selection;
        DirectoryInfo currentDir;
        HUDLabel fileHead;
        private enum State
        {
            FileBrowser,
            Favorites
        }
        private State state = State.Favorites;

        public FileBrowserPage(HUDPage parent, string dir)
            : base(parent)
        {
            InitializeComponents();

            state = State.FileBrowser;

            PopulateQuickLinks();

            PopulateList(dir);

            for (int i = 0; i < linkList.Count; i++)
            {
                if (linkList[i].Tag.ToString() == dir)
                {
                    linkList.SelectedIndex = i;
                }
            }

        }

        public FileBrowserPage(HUDPage parent)
            : base(parent)
        {
            InitializeComponents();
            
            PopulateQuickLinks();
            
            if (linkList.Count > 0)
                PopulateList((string)linkList[0].Tag);
            else
                PopulateList(Directory.GetCurrentDirectory());
        }

        private void InitializeComponents()
        {
            mainBrowser = new HUDContainerSimple();
            mainBrowser.Bounds = new RectangleS(250, 80, Bounds.Width - 300, Bounds.Height - 110);
            mainBrowser.Anchor = Anchor.All;

            quickLinks = new HUDContainerSimple();
            quickLinks.Bounds = new RectangleS(25, 80, 200, Bounds.Height - 110);
            quickLinks.Anchor = Anchor.All ^ Anchor.Right;


            selection = new HUDImage("white.png");
            selection.Size = new SizeS(mainBrowser.Size.Width, 20);
            selection.Anchor = Anchor.All ^ Anchor.Bottom;
            selection.ConstrainProportions = false;
            selection.Alpha = 127;
            selection.Color = ColorS.Black;
            selection.MovementSpeed = 12f;
            selection.ScaleSpeed = 10f;
            Add(selection);

            Add(mainBrowser);
            Add(quickLinks);


            HUDImage browserBackground = new HUDImage("white.png");
            browserBackground.Size = mainBrowser.Size;
            browserBackground.ConstrainProportions = false;
            browserBackground.Color = ColorS.Black;
            browserBackground.Anchor = Anchor.All;
            browserBackground.Alpha = 127;
            mainBrowser.Add(browserBackground);

            HUDImage browserHead = new HUDImage("white.png");
            browserHead.Size = new SizeS(mainBrowser.Size.Width, 32);
            browserHead.Anchor = Anchor.All ^ Anchor.Bottom;
            browserHead.ConstrainProportions = false;
            browserHead.Color = ColorS.Black;
            mainBrowser.Add(browserHead);


            fileHead = new HUDLabel("Filename", "tahoma23b");
            fileHead.Bounds = new RectangleS(25, 0, browserHead.Size.Width - 25, browserHead.Size.Height);
            fileHead.Alignment = Alignment.VCenter;
            mainBrowser.Add(fileHead);


            HUDLabel sizeHead = new HUDLabel("Size", "tahoma23b");
            sizeHead.Bounds = new RectangleS(browserHead.Size.Width - 120, 0, 90, browserHead.Size.Height);
            sizeHead.Alignment = Alignment.VCenter | Alignment.Right;
            sizeHead.Anchor = Anchor.Right;
            mainBrowser.Add(sizeHead);


            HUDLabel extHead = new HUDLabel("Type", "tahoma23b");
            extHead.Bounds = new RectangleS(browserHead.Size.Width - 220, 0, 100, browserHead.Size.Height);
            extHead.Alignment = Alignment.VCenter | Alignment.Center;
            extHead.Anchor = Anchor.Right;
            mainBrowser.Add(extHead);

            HUDImage quickLinkBackground = new HUDImage("white.png");
            quickLinkBackground.Size = quickLinks.Size;
            quickLinkBackground.ConstrainProportions = false;
            quickLinkBackground.Color = ColorS.Black;
            quickLinkBackground.Anchor = Anchor.All;
            quickLinkBackground.Alpha = 127;
            quickLinks.Add(quickLinkBackground);

            HUDImage quickLinkHead = new HUDImage("white.png");
            quickLinkHead.Size = new SizeS(quickLinks.Size.Width, 32);
            quickLinkHead.Anchor = Anchor.All ^ Anchor.Bottom;
            quickLinkHead.ConstrainProportions = false;
            quickLinkHead.Color = ColorS.Black;
            quickLinks.Add(quickLinkHead);


            HUDLabel quickLinkText = new HUDLabel("Quicklinks", "tahoma23b");
            quickLinkText.Bounds = new RectangleS(10, 0, quickLinkHead.Size.Width - 25, quickLinkHead.Size.Height);
            quickLinkText.Alignment = Alignment.VCenter;
            quickLinks.Add(quickLinkText);


            linkList = new HUDMoveList(new SizeS(quickLinkHead.Size.Width, 64), false);
            linkList.Size = new SizeS(quickLinkHead.Size.Width, quickLinks.Size.Height - quickLinkHead.Size.Height);
            linkList.Location = new PointS(0, quickLinkHead.Bounds.Bottom);
            linkList.Anchor = Anchor.All;
            quickLinks.Add(linkList);

            list = new HUDMoveList(new SizeS(browserHead.Size.Width, 20), false);
            list.Size = new SizeS(mainBrowser.Size.Width,mainBrowser.Size.Height - browserHead.Size.Height);
            list.Location = new PointS(0, browserHead.Bounds.Bottom);
            list.Anchor = Anchor.All;
            mainBrowser.Add(list);

        }

        public override void Show()
        {
            Fade(255, 6f);
            base.Show();
        }
        public override void Activate()
        {
            Fade(255, 6f);
            base.Activate();
        }
        public override void Deactivate()
        {

            base.Deactivate();
        }
        public override void Close()
        {
            Fade(0, 6f);
            base.Close();
        }


        public bool PopulateQuickLinks()
        {
            linkList.Clear();

            foreach (QuickLink ql in SharpMedia.Settings.QuickLinks)
            {
                HUDControl c = MakeLinkEntry(ql.Title, ql.Subtitle, ql.Image, ql.Directory);
                c.OnMouseEnter += new EventHandler<MouseEventArgs>(c_OnMouseEnter);
                c.OnMouseUp += new EventHandler<MouseEventArgs>(c_OnMouseUp);
                linkList.Add(c);
            }

            foreach (DriveInfo di in DriveInfo.GetDrives())
            {
                if (di.DriveType == DriveType.Network && !Lizk.Utilities.Net.NetworkDrive.IsNetworkDriveOnline(di.RootDirectory.FullName, 1000))
                {
                    continue;
                }
                
                if (di.IsReady)
                {
                    HUDControl c = MakeLinkEntry(di.Name, di.VolumeLabel, "harddisk.png", di.RootDirectory.FullName);
                    c.OnMouseEnter += new EventHandler<MouseEventArgs>(c_OnMouseEnter);
                    c.OnMouseUp += new EventHandler<MouseEventArgs>(c_OnMouseUp);
                    linkList.Add(c);
                }
            }
            
            linkList.MoveItems(true);
            UpdateSelection(false);
            return true;
        }

        void c_OnMouseUp(object sender, HUDControl.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Command(HUDCommands.Select, null);
            }
        }

        void c_OnMouseEnter(object sender, HUDControl.MouseEventArgs e)
        {
            int index = linkList.IndexOf((HUDControl)sender);
            if (index >= 0)
            {
                state = State.Favorites;
                linkList.SelectedIndex = index;
            }
            UpdateSelection(true);
        }


        public HUDControl MakeLinkEntry(string filename, string subtitle, string imagePath, object tag)
        {
            HUDContainerSimple container = new HUDContainerSimple();
            container.Size = new SizeS(quickLinks.Size.Width, 64);
            container.Anchor = Anchor.All ^ Anchor.Bottom;
            container.Tag = tag;

            HUDImage image = new HUDImage(imagePath);
            image.Bounds = new RectangleS(0, 0, 64, 64);
            container.Add(image);

            HUDLabel fileHead = new HUDLabel(filename, "tahoma23b");
            fileHead.Bounds = new RectangleS(70, 5, container.Size.Width - 20, 25);
            fileHead.Alignment = Alignment.Top;

            container.Add(fileHead);

            HUDLabel sizeHead = new HUDLabel(subtitle, "tahoma14b");
            sizeHead.Bounds = new RectangleS(75, 30, container.Size.Width - 90, 20);
            sizeHead.Alignment = Alignment.Top;
            sizeHead.Anchor = Anchor.Right;
            container.Add(sizeHead);

            return container;
        }



        public bool PopulateList(string filePath)
        {
            if (!Directory.Exists(filePath))
                return false;
            SharpMedia.Engine.Wait();
            list.Clear();

            DirectoryInfo oldDir = currentDir;
            currentDir = new DirectoryInfo(filePath);



            if (currentDir.Parent != null)
            {
                list.Add(MakeFileEntry("..", "", "<DIR>", currentDir.Parent));
                
            }


            list.SelectedIndex = 0;
            fileHead.Text = currentDir.FullName;
            foreach (FileSystemInfo fsi in currentDir.GetFileSystemInfos())
            {
                if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && MediaUtil.GetFiletype(fsi.FullName) != MediaUtil.FileType.Video && MediaUtil.GetFiletype(fsi.FullName) != MediaUtil.FileType.DiscImage)
                    continue;

                if ((fsi.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                    continue;

                list.Add(MakeFileEntry(Path.GetFileNameWithoutExtension(fsi.Name), (fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory ? "" : Path.GetExtension(fsi.FullName), (fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory ? "<DIR>" : Math.Round(((FileInfo)fsi).Length / 1048576f, 0) + " MB", fsi));
                if (oldDir != null && oldDir.FullName.ToLower() == fsi.FullName.ToLower())
                {
                    list.SelectedIndex = list.Count;
                }
            }
            
            list.StartIndex = list.SelectedIndex - list.VisibleItems > 0 ?list.SelectedIndex - list.VisibleItems:0 ;
            list.MoveItems(true);
            
            UpdateSelection(false);
            SharpMedia.Engine.Resume();

            return true;
        }

        public HUDControl MakeFileEntry(string filename, string ext, string size, object tag)
        {
                HUDContainerSimple container = new HUDContainerSimple();
                container.Size = new SizeS(mainBrowser.Size.Width, 20);
                container.Anchor = Anchor.All ^ Anchor.Bottom;
                container.Tag = tag;
                container.OnMouseEnter += new EventHandler<MouseEventArgs>(container_OnMouseEnter);
                container.OnMouseUp += new EventHandler<MouseEventArgs>(c_OnMouseUp);

                HUDLabel sizeHead = new HUDLabel(size, "tahoma20b");
                sizeHead.Bounds = new RectangleS(container.Size.Width - 120, 0, 95, container.Size.Height);
                sizeHead.Alignment = Alignment.VCenter | Alignment.Right;
                sizeHead.Anchor = Anchor.Right;
                sizeHead.CharacterOffset = new PointS(0, -3);
                container.Add(sizeHead);


                HUDLabel extHead = new HUDLabel(ext, "tahoma20b");
                extHead.Bounds = new RectangleS(container.Size.Width - 220, 0, 100, container.Size.Height);
                if (!string.IsNullOrEmpty(extHead.Text))
                    extHead.Text = extHead.Text.Substring(1);
                extHead.Alignment = Alignment.VCenter;
                extHead.Anchor = Anchor.Right;
                extHead.CharacterOffset = new PointS(0, -3);
                container.Add(extHead);

                HUDLabel fileHead = new HUDLabel(filename, "tahoma20b");
                fileHead.Bounds = new RectangleS(25, 0, container.Size.Width - 245, container.Size.Height);
                fileHead.CharacterOffset = new PointS(0, -3);    
            fileHead.Alignment = Alignment.VCenter;
                container.Add(fileHead);
            return container;
        }

        void container_OnMouseEnter(object sender, HUDControl.MouseEventArgs e)
        {

            int index = list.IndexOf((HUDControl)sender);
            if (index >= 0)
            {
                list.SelectedIndex = index;
                state = State.FileBrowser;
            }
            UpdateSelection(true);
        }

        public void UpdateSelection(bool animate)
        {
            switch (state)
            {
                case State.FileBrowser:
                    if (list.Count > 0)
                    {
                        if (animate)
                        {
                            selection.Destination = mainBrowser.Location + list.Location + list.Selection.Location;
                            selection.DestinationSize = new SizeS(mainBrowser.Bounds.Width, 20);
                        }
                        else
                        {
                            selection.Location = selection.Destination = mainBrowser.Location + list.Location + list.Selection.Location;
                            selection.Size = selection.DestinationSize = new SizeS(mainBrowser.Bounds.Width, 20);

                        }

                        if (animate)
                        {
                            selection.Fade(127, 6f);
                        }
                        else
                            selection.Alpha = 127;
                    }
                    else
                    {
                        if (animate)
                            selection.Fade(0, 6f);
                        else
                            selection.Alpha = 0;
                    } 
                    
                    break;
                case State.Favorites:
                    if (list.Count > 0)
                    {
                        if (animate)
                        {
                            selection.Destination = quickLinks.Location + linkList.Location + linkList.Selection.Location;
                            selection.DestinationSize = new SizeS(quickLinks.Bounds.Width, 64);
                        }
                        else
                        {
                            selection.Location = selection.Destination = quickLinks.Location + linkList.Location + linkList.Selection.Location;
                            selection.Size = selection.DestinationSize = new SizeS(quickLinks.Bounds.Width, 64);

                        }

                        if (animate)
                        {
                            selection.Fade(127, 6f);
                        }
                        else
                            selection.Alpha = 127;
                    }
                    else
                    {
                        if (animate)
                            selection.Fade(0, 6f);
                        else
                            selection.Alpha = 0;
                    }
                    break;
                default:
                    break;
            }



        }

        public override void Command(HUDCommands command, object tag)
        {
            switch (command)
            {
                case HUDCommands.Up:
                    if (state == State.FileBrowser)
                    {
                        list.SelectedIndex--;
                    }
                    else
                        linkList.SelectedIndex--;
                    UpdateSelection(true);
                    break;
                case HUDCommands.Down:
                    if (state == State.FileBrowser)
                    {
                        list.SelectedIndex++;
                    }
                    else
                        linkList.SelectedIndex++;
                    UpdateSelection(true);
                    break;
                case HUDCommands.Left:
                case HUDCommands.Right:
                    if (state == State.FileBrowser)
                        state = State.Favorites;
                    else
                        state = State.FileBrowser;
                    UpdateSelection(true);
                    break;
                case HUDCommands.PageUp:
                    if (state == State.FileBrowser)
                    {
                        list.SelectedIndex -= 10 ;
                    }
                    else
                        linkList.SelectedIndex-=10;

                    UpdateSelection(true);
                    break;
                case HUDCommands.PageDown:
                    if (state == State.FileBrowser)
                    {
                        list.SelectedIndex += 10;
                    }
                    else
                        linkList.SelectedIndex+=10;
                    UpdateSelection(true);
                    break;
                case HUDCommands.Select:
                    if (state == State.FileBrowser)
                    {
                        if (list.SelectedControl != null)
                        {
                            FileSystemInfo fsi = ((FileSystemInfo)list.SelectedControl.Tag);
                            if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                            {
                                PopulateList(fsi.FullName);
                            }
                            else
                            {
                                VideoList vl = new VideoList();
                                foreach (var item in list)
                                {
                                    FileSystemInfo fs = (FileSystemInfo)item.Tag;
                                    if (fsi is FileInfo)
                                    {
                                        vl.Add(new VideoSource(fs.Name, fs.FullName));
                                        if (item == list.SelectedControl)
                                            vl.SelectedIndex = vl.Count - 1;
                                    }
                                }



                                PlayerPage fpp = new PlayerPage(this, vl);
                                SharpMedia.Navigate(fpp);
                            }
                        }
                    }
                    else
                    {
                        if (linkList.SelectedControl != null)
                        {
                            string path = ((string)linkList.SelectedControl.Tag);
                            if (Directory.Exists(path))
                            {
                                PopulateList(path);
                            }
                        }
                    
                    }
                    break;
                case HUDCommands.Back:
                    if (state == State.FileBrowser && currentDir != null && currentDir.Parent != null)
                    {
                        PopulateList(currentDir.Parent.FullName);
                    } else if (state == State.Favorites)
                        SharpMedia.Back();
                    break;
                case HUDCommands.Menu:
                    break;
                default:
                    if (parent != null)
                        parent.Command(command, tag);
                    break;
            }
        }
    }


}
